/*
 * @Author: Zhang Kai
 * @Date: 2021-10-20 10:39:44
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-06 14:53:44
 * @FilePath: /metricsx-standard-ui/src/views/indexManage/modifiermanage/index.tsx
 */
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch,
  computed,
  watchEffect
} from 'vue';
import './style/index.scss';
import Table from '@/components/Table/index';
import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import SearchForm from './components/searchForm';
import CreateForm from './components/createForm';
import { ECustomColumn } from '@/utils/constants';
import { useStore } from '@/store';
import BatchOperates from '@/components/batchOperates/index.vue';
import CustomColumn from '@/components/CustomColumn/index';
import shrinkLeft from '@/assets/images/shrinkLeft.svg';
import activeShrinkLeft from '@/assets/images/activeShrinLeft.svg';
import Bulk from '@/components/Bulk/index';
import API from '@/services';
import GroupTree from '@/components/GroupTree';
import { rebuildObject } from '@/utils/util';
import { useTableFetch, useResource } from '@/hooks/base';
import _ from 'lodash';

interface extra {
  sortBy: any;
  order: any;
}

const ModifierManage = defineComponent({
  name: 'ModifierManage',
  components: { BatchOperates },
  setup: (props, { slots, attrs, emit }) => {
    // 获取api
    const {
      modifier: {
        postModifierGroup,
        putModifierGroup,
        getModifierGroupRoot,
        deleteModifierGroupById
      }
    } = API;
    const store = useStore();

    const tableFef = ref();

    const TableLoading: any = ref(false);

    const shrinkIcon = ref(shrinkLeft);

    /* 创建修饰词  form ref */
    const createFormRef = ref();

    /* 查询 form ref */
    const formQuery = ref({ groupId: '' });
    /* 抽屉开关 */
    const visible = computed(() => store.state.modifier.drawerVisible);

    /* 名称重复字段及文案 */
    const errorData = ref([]);

    /* 多选 */
    const multipleSelection = reactive({ data: [] });

    /* 编辑 创建判断 */
    const isEdits: any = ref(false);

    /* 编辑数据 */
    const editData: any = reactive({ obj: {} });

    /* 收缩状态 */
    const toggle = ref(false);

    /* 下载模版Url */
    const downloadUrl = ref('');

    /* table Column */
    const tableColumn: any = ref([
      {
        label: 'ID',
        keys: 1,
        sortable: 'custom'
      },
      {
        label: '创建时间',
        keys: 8,
        sortable: 'custom'
      },
      {
        label: '操作',
        keys: 10,
        default: ({ row }: any) => {
          return (
            <div>
              <el-button type="text" onClick={() => edit(row?.id)}>
                编辑
              </el-button>

              <el-button
                type="text"
                disabled={!row.deletable}
                onClick={() => deleteModifier(row?.id)}
              >
                删除
              </el-button>
            </div>
          );
        }
      }
    ]);

    const newTableColumn: any = ref([]);

    const settings: any = ref([]);

    // 分组key
    const groupKey = ref(1);

    const service = (p: any) =>
      API.modifier.postModifierList({
        ...p
      });
    const { data, currentPage, pageSize, total, loading, run, refresh } =
      useTableFetch(service, true);
    // 排序
    const sortTable = (obj: any) => {
      const extra: extra = { sortBy: undefined, order: undefined };
      if (obj.prop) {
        const order = obj.order === 'ascending' ? 1 : 2;
        extra.sortBy = obj.prop;
        extra.order = order;
      }
      run({ ...formQuery.value, ...extra });
    };
    // 多选
    const handleSelectionChange = (v: any) => {
      multipleSelection.data = v;
    };

    /* 抽屉关闭 */
    const handleClose = () => {
      store.commit('modifier/toggleDrawerVisible', false);
      setTimeout(() => {
        isEdits.value = false;
      }, 500);

      editData.obj = {};
      errorData.value = [];
    };
    // 提交
    const submit = async (form: any) => {
      createFormRef.value.validate(async (bol: any) => {
        if (!bol) return;
        try {
          if (isEdits.value) {
            const groupId = form?.groupId;
            const { code, data }: any = await API.modifier.putModifierById(
              { id: editData.obj.id },
              {
                ...form,
                groupId: groupId.length ? groupId[groupId.length - 1] : groupId
              }
            );
            if (code === 200) {
              ElMessage.success('编辑成功');
              groupKey.value++;
              handleClose();
              run();
            } else {
              errorData.value = data;
            }
          } else {
            const { code, data }: any = await API.modifier.postModifier({
              ...form
            });
            if (code === 200) {
              ElMessage.success('创建成功');
              groupKey.value++;
              handleClose();
              run();
            } else {
              errorData.value = data;
            }
          }
        } catch (error) {
          console.warn(error);
        }
      });
    };
    //编辑
    const edit = async (id: any) => {
      try {
        const { code, data } = await API.modifier.getModifierById({
          id
        });
        if (code === 200) {
          editData.obj = data;
        }
      } catch (error) {
        console.log(error);
      }
      isEdits.value = true;
      store.commit('modifier/toggleDrawerVisible', true);
    };
    // 删除
    const deleteModifier = (id: any) => {
      ElMessageBox.alert('', '是否确认删除该修饰词?', {
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'message-box-del'
      })
        .then(async () => {
          try {
            const { code, data, msg } = await API.modifier.deleteModifierById({
              id
            });
            if (code === 200) {
              ElMessage.success('删除成功');
              groupKey.value++;
            } else {
              ElMessage.error(msg);
            }
            run();
          } catch (error) {
            console.log(error);
          }
        })
        .catch(() => {
          ElMessage.info('取消删除');
        });
    };

    /* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.modifier
        });
        if (code === 200) {
          settings.value = data?.settings;
          const column = data?.settings?.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            return {
              ...tableColumn.value[columnIndex],
              ...v,
              columnKey: Date.now()
            };
          });
          column.unshift({
            type: 'selection',
            width: '55',
            isCheck: true
          });
          newTableColumn.value = _.compact(column);
        }
      } catch (error) {
        console.log(error);
      }
    };
    const handleBatchOperate = async (v: any) => {
      if (multipleSelection.data.length === 0) {
        ElMessage.warning('请勾选操作项，再进行批量操作');
        return false;
      }
      TableLoading.value = true;
      switch (v) {
        case 'delete':
          ElMessageBox.alert('', '是否确认删除已选修饰词?', {
            confirmButtonText: '确认删除',
            showCancelButton: true,
            confirmButtonClass: 'message-box-del'
          })
            .then(async () => {
              const ids: any = multipleSelection.data.map((d: any) => d.id);
              try {
                const { code } = await API.modifier.postModifierBatchDelete(
                  ids
                );
                if (code === 200) {
                  ElMessage.success('批量删除成功');
                  groupKey.value++;
                }
                run();
              } catch (error) {
                console.log(error);
              }
            })
            .catch(() => {
              ElMessage.info('批量取消删除');
            });
          break;
      }
      TableLoading.value = false;
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.modifier,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          ElMessage.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };

    onMounted(() => {
      getCustomColumnApi();
      run();
    });

    return () => {
      return (
        <div class="modifier_container">
          <div
            class="modifier_container-left"
            style={{ width: toggle.value ? '0px' : '210px' }}
          >
            <img
              class={toggle.value && 'shrinkRight'}
              onClick={() => (toggle.value = !toggle.value)}
              src={shrinkIcon.value}
              onMouseenter={() => (shrinkIcon.value = activeShrinkLeft)}
              onMouseout={() => (shrinkIcon.value = shrinkLeft)}
              alt=""
            />
            <GroupTree
              titles="修饰词分组管理"
              groupKey={groupKey.value}
              listFn={getModifierGroupRoot}
              delFn={deleteModifierGroupById}
              reNameFn={putModifierGroup}
              addFn={postModifierGroup}
              onGetTreeNode={({ id }: any) => {
                if (id === 'new') return;
                formQuery.value.groupId = id;
                run(rebuildObject({ ...formQuery.value }));
              }}
            ></GroupTree>
          </div>
          <div class="modifier_container-right">
            <SearchForm
              search={(form: any) => {
                formQuery.value = form;
                formQuery.value.groupId = '';
                run(rebuildObject(form));
              }}
            />
            <div class="table-operate">
              <div class="CustomColumn-operate-wrap">
                <CustomColumn
                  onConfirm={(v: any) => customColumnConfirm(v)}
                  tableColumn={settings.value}
                />
                <div class="checkLength">
                  已选择<b>{multipleSelection.data.length}</b>个修饰词
                </div>
              </div>
              <div class="batch-operate-wrap">
                <Bulk
                  downloadList={[
                    { command: 'modifiermanage', text: '修饰词下载' }
                  ]}
                  onCommand={() => {
                    downloadUrl.value = '/tmplate/download/';
                  }}
                  downloadUrl={downloadUrl.value}
                  tmpCode={'2'}
                  onSuccess={() => {
                    run({ ...formQuery.value });
                    groupKey.value++;
                  }}
                />
                <BatchOperates
                  v-loading={TableLoading.value}
                  opKeys={['delete']}
                  onBatchOperate={handleBatchOperate}
                  disabled={multipleSelection.data.length === 0}
                />
              </div>
            </div>
            <Table
              tableFef={tableFef}
              showCheckbox={true}
              v-loading={loading.value}
              onSortChange={sortTable}
              data={data.value}
              column={newTableColumn.value.filter((v: any) => v.isCheck)}
              onSelectionChange={handleSelectionChange}
              onPageCurrentChange={(page: number) => {
                run({
                  ...rebuildObject(formQuery.value),
                  pageNum: page,
                  pageSize: pageSize.value
                });
              }}
              onPageSizeChange={(size: number) => {
                run({
                  ...rebuildObject(formQuery.value),
                  pageSize: size,
                  pageNum: currentPage.value
                });
              }}
              pagination={{
                total: total.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
              }}
            />

            <el-drawer
              custom-class="modifier-drawer"
              v-model={visible.value}
              title={isEdits.value ? '编辑' : '创建修饰词'}
              close-on-click-modal={false}
              append-to-body={true}
              direction="rtl"
              before-close={handleClose}
              onClosed={() => (isEdits.value = false)}
              lock-scroll={false}
            >
              {visible.value && (
                <CreateForm
                  editData={editData.obj}
                  isEdits={isEdits.value}
                  createFormRef={createFormRef}
                  errorData={errorData.value}
                  onHandleClose={handleClose}
                  onSubmit={submit}
                />
              )}
            </el-drawer>
          </div>
        </div>
      );
    };
  }
});

export default ModifierManage;
